<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>       
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!DOCTYPE html>
<html>
<head>
<link rel="shortcut icon" href="${_resources}/logo.png"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">                                            
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />  
<title>项目模板类型定义</title>
<%@ include file="/WEB-INF/jsp/common/inc.jsp" %>
<script type="text/javascript">

var selectDoc ;
var selectDocId ="";
var selectedList ="";
if('${docListjson}'!=''){
selectedList=JSON.parse('${docListjson}');	
}
$(function(){
	selectDoc = eval('(${proDocJson})');
	$.each(selectDoc, function (i, item) {
		if(selectDocId.length==0){
			selectDocId = item.id;
		}else{
			selectDocId +=","+item.id;
		}
	});
	
	$("#documentId").val(selectDocId);
	selectDocumentTemplateList();
})



//新增适用范围
function selectCreate(value){
	if(value=="newCreate"){
		/* $("#popIframe").empty();	
		$("#popDiv").dialog({
			title:'创建项目模板类型',
			autoOpen: true,
			modal: true,	
			height: 300,
			width: 430
		});	
		$("#popIframe").attr("width","100%");
		$("#popIframe").attr("height","95%");
		$("#popIframe").attr("src","${_baseUrl}/applicableScopeController/newApplicableScope");	 */	
		layerIndex =layer.open({
			  type: 2, 
			  title:'修改项目模板信息',
			  area: ['450px', '300px'],
			  fixed: false, //不固定
			  maxmin: true,
			  shim: true,
			  content: "${_baseUrl}/applicableScopeController/newApplicableScope?rand="+Math.random(),
			});
	}
}

function getApplicationScope(){
	var path="${_baseUrl}/applicableScopeController/SelectAllApplicableScope";
	$.ajax({    
		type: "POST",    
		async: false,    
		url:path,
		dataType:"json",    
		success: function (data) {   
			var jsonObj=eval("("+data.message+")");
			var options="";
			if(jsonObj.length>0){
				options+="<option>请选择</option>";
				$.each(jsonObj, function (i, item) {
					options+="<option value='"+item.scopeName+"'>"+item.scopeName+"</option>";
			 	});
			}
			$("#applicationScope").html(options);
			
		}   
	}); 		
	
}
//验证样式输出文档
function checkSelectOut(){	
	var select = $("select[name='styleOutTemplate']");
	var options = $(select).find("option");
	for(var i =0;i<options.length;i++){
		if($(options[i]).prop("selected")=="selected"||$(options[i]).prop("selected")==true){
			var value = $(options[i]).val();
			if(value=="请选择"){
				return "请选择样式模板名称";
			}else{
				return true;
			}
		}
	}
	
}
//验证样式定义文档
function checkSelectSet(){	
	var select = $("select[name='styleSetTemplate']");
	var options = $(select).find("option");
	for(var i =0;i<options.length;i++){
		if($(options[i]).prop("selected")=="selected"||$(options[i]).prop("selected")==true){
			var value = $(options[i]).val();
			if(value=="请选择"){
				return "请选择样式模板名称";
			}else{
				return true;
			}
		}
	}
	
}
//验证适用范围的下拉框
function checkSelectScope(){	
	var select = $("select[name='applicationScope']");
	var options = $(select).find("option");
	var value="";
	for(var i =0;i<options.length;i++){
		if($(options[i]).prop("selected")=="selected"||$(options[i]).prop("selected")==true){
			value = $(options[i]).val();
			
		}
	}

	if(value=="请选择"){
		return "请选择适用范围";
	}else{
		return true;
	}
}


//选中复选框之后将文档id存储到input中，提交到后台去
function selectDocument(){	
	var inputs =$("input:checked");
	var documentId ="";
	for(var i =0;i<inputs.length;i++){
		if(documentId.length==0){
			documentId=$(inputs[i]).val();
		}else{
			documentId+=","+$(inputs[i]).val();
		}
	}	
	
	$("#documentId").val(documentId);
	
}

//取消和关闭调用的方法
function cancelAndClose(){
	parent.closeWin();
}

$(function(){
	$("#form").validationEngine({
		autoHidePrompt:true,//自动隐藏
		showOnMouseOver:true,//当鼠标移出时触发
		promptPosition:'bottomLeft',//提示信息的位置
		inlineValidation: true,//是否即时验证，false为提交表单时验证,默认true  
		failure : function() {
		    layer.message("验证失败，请检查");
			return false;  
		},//验证失败时调用的函数
		ajaxFormValidation: true,//开始AJAX验证
		success : function() {
		//	$("#addForm").submit();
		}//验证通过时调用的函数 
		//onAjaxFormComplete: ajaxValidationCallback
	});
})

function formSubmit(){
	var options = {
			dataType:"json",
			success:function(json){
				if(json.code=='1'){
					layer.msg(json.message,{shift:5,time:1500},function(){
						parent.closeWin();
						parent.refreshTable();
						if(typeof(parent.parent.AgainGetProjectTemplate) != "undefined"){
							parent.parent.AgainGetProjectTemplate();
						}
					});
				}else{
					layer.msg("系统错误,请联系管理员");
					parent.closeWin();
				}
			},
			error:function(json){
				layer.msg("系统错误,请联系管理员");
			}
		};

	var objects = selectedList;
	var stageId = "";
	if($("#form").validationEngine('validate')){
		 if(objects.length>0){
			 for(var i =0;i<objects.length;i++){
					if(documentId==""){
						documentId=objects[i].documentId;
						stageId = objects[i].stageId;
					}else{
						documentId+=","+objects[i].documentId;
						stageId += ","+objects[i].stageId;
					}
				}
			$("#projectTypeId").val("${ProjectTypeId}");
			$("#stageId").val(stageId);
			$("#documentId").val(documentId);
		 }
		 var documentId=$("#documentId").val();
		if(documentId.length>0){
			$("#submit").attr("onclick","");
			$('#form').ajaxSubmit(options);
		}else{
			layer.msg("请至少选择一份文档");
		}
	}
}

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}
 
function selectSearch(){
	//var docObj  = "${listDocumentTemplate }";
	var name  = $("#selectByTemplateName").val();
	var source =$("#document_source").val();
	var path ="${_baseUrl}/projectTemplateTypeController/searchByNameSource";
	var options="";
	$.ajax({    
		type: "POST",    
		async: false,    
		url:path,
		data:{
			"name":name,
			"source":source
		},
		dataType:"json",    
		success: function (json) {   
			if(json.code=="1"){
				var docObj = eval(json.message);
				$.each(docObj, function (i, item){
					if(judgeSelect(item.id)){
						options +="<tr> <td><input name ='document' value="+item.id+" onclick='judgeSelectDoc(this);'  type ='checkbox' checked='checked' /></td>";
					}else{
						options +="<tr> <td><input name ='document' value="+item.id+" onclick='judgeSelectDoc(this);'  type ='checkbox' /></td>";
					}
					options +="<td>"+(i+1)+"</td>"
					options +="<td>"+item.documentTemplateName+"</td>"
					options +="<td>"+item.documentType+"</td>"
					options +="<td>"+item.applicationScope+"</td>"
					var docSource = item.source;
					if(docSource =="初始化"){
						options +="<td>组织级文档模板</td>"
					}
					if(docSource =="自定义"){
						options +="<td>用户级文档模板</td>"
					}
					if(docSource =="文档范本库"){
						options +="<td>文档范本库</td>"
					}
					options +="</tr>";
				})
				var size = $(".tablebox thead tr:first-child>td").length;
				if(options == ''){
					options += "<tr><td colspan='6'>没有符合条件的记录</td></tr>";    /* 当搜索条件为空时给出提示  */
				}
				$("#docList").html(options);
			}
		} 
		
	});
}
document.onkeydown=function(event) { 
	e = event ? event :(window.event ? window.event : null); 
	if(e.keyCode==13){ 
		selectSearch(); 
	} 
}
function judgeSelect(id){
	selectDoc = eval('(${proDocJson})');
	var result =false;
	$.each(selectDoc, function (i, item) {
		if(item.id==id){
			result=true;
		}
	});
	if($("#documentId").val().indexOf(id)>=0){
		result = true;
	}
	return result;
	
}

function judgeSelectDoc(obj){
	var documentId = $("#documentId").val();
	var inputId = $(obj).val();
	if($(obj).prop("checked")==true){
		if(documentId.indexOf(inputId)>=0){
			return;
		}else{
			$("#documentId").val(documentId+","+inputId);
		}
	}else{
		if(documentId.indexOf(inputId)>=0){
			$("#documentId").val(documentId.replace(inputId,""));
		}else{
			return;
		}
	}
}

//根据项目类型选择项目模板
function selectDocumentTemplateList(){
	var projectType="${ProjectTypeId}";
	//$("#secretInvolvedLevelList").bootstrapTable('refresh', {url: '${_baseUrl}/projectTemplate/selectDocumentTemplateByProjectType' });
	if(projectType != null && projectType != "" && projectType != undefined){
		document.getElementById("kdDocument").style.display="none";
		document.getElementById("kdDocument1").style.display="none";
		document.getElementById("ktDocument").style.display="block";
		$("#secretInvolvedLevelList").bootstrapTable({
			url : '${_baseUrl}/KmProjectDocumentTemplateController/selectDocumentTemplateByProjectType?rand='+Math.random(),
			pagination: true,
			pageList: [5, 10, 20, 50],
	  		queryParams: queryParams,
	  		clickToSelect: true,
	  		onLoadSuccess : function(data) {
	  		 	var cellIndex=parseInt($(".table_inline th").length);
	            $(".table_inline tr td").each(function(){
	                if(this.cellIndex != cellIndex){
	                    $(this).attr("title",$(this).text());
	                }
	            });
	  			var rows = $("#secretInvolvedLevelList tbody tr");
	  			var docShouleBeChecked =selectedList;
	  			var data = $('#secretInvolvedLevelList').bootstrapTable('getData', true);
	  			for(var i = 0;i < docShouleBeChecked.length;i ++){
	  				for(var j = 0; j < data.length;j ++){
	  					if(docShouleBeChecked[i].documentId ==data[j].documentId 
	  							&& docShouleBeChecked[i].projectTypeName == data[j].projectTypeName
	  							&& docShouleBeChecked[i].stageId == data[j].stageId
	  							){
	  						$('#secretInvolvedLevelList').bootstrapTable('check', j);
	  					}
	  				}
	  			}
	  		},
			onCheck: function(row){

				var ids = new Array();
				for(var i = 0;i<selectedList.length;i++){
					if(selectedList[i] != undefined){
						ids.push(selectedList[i].documentId);
					}            		
				}
				var idsString = ids.join(",");
				if(!(idsString.indexOf(row.documentId)>=0)){
					selectedList.push(row);
				}				
			},
			onUncheck: function(row){
				for(var i = 0;i<selectedList.length;i++){
					if(selectedList[i] != undefined){
						if(row.documentId == selectedList[i].documentId){
							selectedList.splice(i,1);            		
						}
					}
				}
			},
			onCheckAll: function(rows){
				//var selected = $("#testItemList").bootstrapTable("getSelections");
				var selected = this.data;
				var ids = new Array();
				for(var i = 0;i<selectedList.length;i++){
					if(selectedList[i] != undefined){
						ids.push(selectedList[i].documentId);
					}
				}
				var idsString = ids.join(",");
				for(var j = 0;j<selected.length;j++){
					if(!(idsString.indexOf(selected[j].documentId)>=0)){
						selectedList.push(selected[j]);
					}
				}
			},
			onUncheckAll: function(rows){   
				//如何获取已经取消的行
				var selected = this.data;
				var ids = new Array();
				for(var i = 0;i<selected.length;i++){
					ids.push(selected[i].documentId);
				}
				var idsString = ids.join(",");
			/* 	for(var j = 0;j<selectedList.length;j++){
					if(selectedList[j] != undefined){
						if(idsString.indexOf(selectedList[j].id)>=0){
							delete selectedList[j]; 
						}
					}            		
				} */
				for(var j = selectedList.length - 1;j>=0;j--){
					if(selectedList[j] != undefined){
						if(idsString.indexOf(selectedList[j].documentId)>=0){
							selectedList.splice(j,1); 
						}
					}            		
				}
			},
	        columns: [{
				 field: 'checked',
				 checkbox: true,
				 width: 30,
				 height: 50,
				 align: 'center',
				 formatter: function(value, row, index){
						var ids = new Array();
						for(var i = 0;i<selectedList.length;i++){
							if(selectedList[i] != undefined){
								ids.push(selectedList[i].documentId);
							}                 		
						}
						var idsString = ids.join(",");
						 if(idsString.indexOf(row.documentId) >= 0){
							return true;
						 }else{
							return false;
						 }
					 }
			 }, {
	            field: 'documentId',
	            title: 'documentId',
	            visible:false,
	            width: 5,
	        },
	        {
	            field: 'id',
	            title: 'id',
	            visible:false,
	            width: 5,
	        },{
	            field: 'documentName',
	            title: '文档模板名称',
	            width: 200,
	        },{
	            field: 'templateSortKTs',
	            title: '模板类型',
	            width: 85 ,
	            formatter:function(value,row,index){
			           if(row.templateSortKTs.length > 0 && row.templateSortKTs[0].sortName != null ){
			                		var typeStr = "";
			                		for(var i = 0; i < row.templateSortKTs.length; i ++){
			                			if(row.templateSortKTs[i].sortName != null){
			                				typeStr += row.templateSortKTs[i].sortName+";";
			                			}
			                		}
			                		typeStr1 = typeStr.substring(0,typeStr.length-1);
			                		return typeStr1;
			            	}
			            }
	        },{
	            field: 'applicationScope',
	            title: '文档<br>适用范围',
	            width: 100,
	        },{
	            field: 'projectTypeName',
	            title: '项目类型',
	            width: 85,
	        },{
	            field: 'stageName',
	            title: '阶段名称',
	            width: 85,
	        }, {
	            field: 'stageId',
	            title: 'stageId',
	            visible:false,
	            width: 5,
	        }],
	  /*       onLoadSuccess : function(data) {
	        	var cellIndex=parseInt($(".table_inline th").length);
	            $(".table_inline tr td").each(function(){
	                if(this.cellIndex != cellIndex){
	                    $(this).attr("title",$(this).text());
	                }
	            });
	  		}, */
	  		
	    });
	}else{
		document.getElementById("ktDocument").style.display="none";
		document.getElementById("kdDocument").style.display="block";
		document.getElementById("kdDocument1").style.display="block";
	}
}
function queryParams(params){
	return {
	    pageSize: params.limit,
	    pageNo: params.pn,
	    sort : params.sort,
	    order : params.order,
	    projectType:"${ProjectTypeId}"
   };
} 
</script>

</head>
<body>
<form action="${_baseUrl}/KmProjectDocumentTemplateController/saveAlter" method="post" name="form" id="form">  
 <input type="hidden" name="documentId" id="documentId" value="" />
 <input type="hidden" name="id" id="id" value="${projectTemplate.id}" />
<input type="hidden" name="token" value="${token}" />
<input type="hidden" name="stageId" id="stageId" value="" />
<input type="hidden" name="projectTypeId" id="projectTypeId" value="" />
 <div class="jbinformation roleshux">
	<table class="table table-bordered submenu_table" style="width:100%">
  <tr>
  	 <td height="50" width="15%" align="center"><span style="color:#f00">*</span> 模板名称</td>
    <td width="35%" valign="middle">
    <div>
    <input type="text" name="projectTemplateName" value="${projectTemplate.projectTemplateName} " disabled="disabled" id="projectTemplateName"  class="nav_input validate[required]">
    </div>
    </td>
    <td height="50" width="15%" align="center"><span style="color:#f00">*</span> 适用范围</td>
    <td width="35%" valign="middle">
    <div>
    <select class="func_select validate[required,funcCall[checkSelectScope]] "  name="applicationScope" id="applicationScope"  style="width:100%; margin:0;" onchange="selectCreate(this.options[this.options.selectedIndex].value)">
          <option>请选择</option>
         <c:forEach items="${listApplicableScope}" var="applicableScope">
			 <option value="${applicableScope.id}"  <c:if test="${applicableScope.id ==projectTemplate.applicationScope}">selected="selected"</c:if>>${applicableScope.application} </option>
		</c:forEach> 
      </select>
      </div>
      </td>
      </tr>
      <tr>
      <td height="50" width="15%" align="center"><span style="color:#f00">*</span> 样式模板名称</td>
    <td width="35%" valign="middle">
    <div>
    <select class="func_select  validate[required,funcCall[checkSelectOut]]"   name="styleOutTemplate" style="width:100%; margin:0;">
           <option>请选择</option>
          <c:forEach items="${listStyleTemplateDefine }" var="styleOutTemplate">
			<c:if test="${styleOutTemplate.styleType=='outSet'}">
				<option title="${styleOutTemplate.styleDocumentName}" value="${styleOutTemplate.id}" <c:if test="${styleOutTemplate.id ==projectTemplate.styleOutTemplate}">selected="true"</c:if> >${styleOutTemplate.styleDocumentName}</option>
			</c:if>
		</c:forEach>
      </select>
      </div>
	</td>
	    <td height="50" width="15%" align="center">项目类型</td>
        <td width="35%" valign="middle">
			<div class="">
                <input type="text" class="nav_input" name="projectType" id="projectType" value="${ProjectType.name}" disabled="disabled">
            </div>
        </td>
  </tr>
</table>

</div>
<div class="func_bar" id="kdDocument">
    	<div class="search_container">
	        <div class="func_search">
	        	<div class="func_search_div"></div>
	            <input type="text" id="selectByTemplateName" name="user_date" value="${searchValue}" placeholder="请输入关键词" />
	            <a class="search_btn" onclick="selectSearch();" id="search" href="javascript:;"></a>
	        </div>
	    </div>
        <select class="func_select" id="document_source" onchange="selectSearch();" style="width:200px;margin-left:20px;height: 29px !important;">
                     	<option value="choice">请选择文档模板来源</option>
                        <option value="1">组织级文档模板</option>
                        <option value="2">用户级文档模板</option>
                        <option value="3">文档范本库</option>
        </select>
</div>

<div style="text-align: center;" id="kdDocument1">
    <table  class="table table-bordered submenu_table">
        <thead>
          <tr>
            <td width="10%">选择</td>
            <td width="10%">序号</td>
            <td width="20%">文档模板名称</td>
            <td width="20%"><span >模板类型</span></td>
            <td width="20%"><span >适用范围</span></td>
            <td width="20%">文档模板来源</td>
          </tr>
         </thead>
           <tbody id = "docList">
          <c:forEach items="${listDocumentTemplate }" var="documentTemplate" varStatus="status">
			<tr>
				<td><input name="document" value="${documentTemplate.id}"  onclick="judgeSelectDoc(this);"  type="checkbox"  
				<c:forEach  items="${list }" var="docTemplate">
				<c:if  test="${documentTemplate.id ==docTemplate.id }" > checked="checked" </c:if>
				</c:forEach> />
				</td>
				<td>${status.count}</td>
				<td>${documentTemplate.documentTemplateName}</td>
				<td>${documentTemplate.documentType}</td>
				<td>${documentTemplate.applicationScope}</td>
				<td><c:if test="${documentTemplate.source=='初始化'}">组织级文档模板</c:if>
				<c:if test="${documentTemplate.source=='自定义'}">用户级文档模板</c:if>
				<c:if test="${documentTemplate.source=='文档范本库'}">文档范本库</c:if></td>
			</tr>		
		</c:forEach>
		</tbody>
    </table>
    
    
</div>
<div style="overflow: auto; width:98%;margin: auto;" id="ktDocument">
<table id="secretInvolvedLevelList" class="table table-bordered table_inline"></table>
</div>
<div class="permission_an mubanclass_an ma mt30" style="margin-top: 14px;margin-bottom: 10px;">
	<shiro:hasPermission name="KmProjectDocumentTemplateController:saveAlter">
       <a href="javascript:;"  id="submit"  onclick="formSubmit();" class=" per_baocun">保 存</a>
    </shiro:hasPermission>
    <shiro:hasPermission name="KmProjectDocumentTemplateController:close5">
        <a href="javascript:;" class=" per_gbi" onclick="cancelAndClose();">取 消</a>
    </shiro:hasPermission>

</div>
 <div id="popDiv" style="display: none;">
		<iframe id="popIframe" border="0" frameborder="no"></iframe>
	</div>                             	  	
</form>
</body>
</html>